/**
 * https://leetcode-cn.com/problems/number-of-islands/
 * @param {character[][]} grid
 * @return {number}
 */
 var numIslands = function(grid) {
  let cols = grid[0] ? grid[0].length : 0;
  let rows = grid.length;
  let count = 0;
  for (let i = 0; i < rows; i++) {
      for (let j = 0; j < cols; j++) {
          if (grid[i][j] !== '0') {
              count++;
              flipLands(i, j);
          }
      }
  }

  function flipLands(row, col) {
      // terminator
      if (row < 0 || col < 0 || row > rows - 1 || col > cols - 1 || grid[row][col] === '0') {
          return;
      }
      // process current
      grid[row][col] = '0';
      // drill down
      flipLands(row - 1, col);
      flipLands(row, col -1);
      flipLands(row + 1, col);
      flipLands(row, col + 1);
  }
  return count;
};